﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace IPC.Communication.Framework.Core
{
    public static class NetSupport
    {
        internal const int SocketBufferSize = 16384;

        internal static byte[] ReadBytesFromSocket(Socket socket, int receive, Action<long, long> reportProgress = null)
        {
            byte[] array = new byte[receive];
            ReceiveBytesFromSocket(socket, array, 0, receive, reportProgress);
            return array;
        }

        internal static void ReceiveBytesFromSocket(Socket socket, byte[] buffer, int offset, int length, Action<long, long> reportProgress = null)
	    {
		    int num = 0;
		    while (true)
		    {
			    if (num < length)
			    {
				    int size = Math.Min(length - num, 16384);
				    int num2 = socket.Receive(buffer, num + offset, size, SocketFlags.None);
				    num += num2;
				    if (num2 == 0)
				    {
					    break;
				    }
                    if (reportProgress != null)
                    {
                        reportProgress.Invoke(num, length);
                    }
				    continue;
			    }
			    return;
		    }
		    throw new RemoteCloseException();
	    }
    }
}
